//
//  GYConfirmOrderViewController.m
//  GoodLuck
//
//  Created by apple on 2018/3/20.
//  Copyright © 2018年 yunjiazhineng. All rights reserved.
//

#import "GYConfirmOrderViewController.h"
#import "GYBasePopoverViewController.h"
#import "PopoverAnimation.h"
#import "GYSearchViewController.h"
#import "GYSystemMessageViewController.h"
#import "GYOrderAddressCell.h"
#import "GYorderSecondCell.h"
#import "GYOrderGoodsCell.h"
#import "GYpayView.h"
#import "GYOrderIngetralCell.h"
#import "GYpayView.h"
#import "GYNetWorkTools.h"
#import "GYRecriveAddress.h"
#import "GYPayMethodViewController.h"
#import "GYInvoiceViewController.h"
#import "GYConfirmOrderAddressViewController.h"
#import "GYShopHomeViewController.h"
#import "GYShopingCart.h"
#import "GYShopingCartGoods.h"
#import "GYPayMethodSelectView.h"
//#import "GYPayViewController.h"
#import "XLPasswordView.h"
#import "GYPayment.h"
#import <AlipaySDK/AlipaySDK.h>
#import "WXApi.h"

@interface GYConfirmOrderViewController ()<UITableViewDelegate,UITableViewDataSource,XLPasswordViewDelegate>

/** 表格 */
@property (nonatomic, strong) UITableView *tableView;

/** 动画代理 */
@property (nonatomic, strong) PopoverAnimation *animationDelegate;

/** 付款视图 */
@property (nonatomic, strong) GYpayView *payView;

/** 收货之地模型 */
@property (nonatomic, strong) GYRecriveAddress *addressModel;

/** titles */
@property (nonatomic, strong) NSArray *titles;

/** 方式 */
@property (nonatomic, strong) NSMutableArray *methods;

/** 订单里面的商店数量商品 */
@property (nonatomic, strong) NSArray *storeList;

/** 店铺留言 */
@property (nonatomic, strong) NSString *storeMsg;

/** 支付选择界面视图 */
@property (nonatomic, strong) GYPayMethodSelectView *payMethodSelectView;

/** 确认订单信息 */
@property (nonatomic, strong) NSDictionary *cachesOrderInfo;

/** 当前发票id */
@property (nonatomic, strong) NSString *invoice_id;

/** 缓存店铺留言 */
@property (nonatomic, strong) NSMutableDictionary *cachesStoreMsg;

/** 个人总积分 */
@property (nonatomic, assign) int member_points;

/** 用户输入积分 */
@property (nonatomic, strong) NSString *inputIngetral;

//代表订单是否提交成功
@property (nonatomic, getter=isSubmit) BOOL submit;

/**  */
@property (nonatomic, strong) NSString *offpay_hash;

/** <#description#> */
@property (nonatomic, strong) NSString *offpay_hash_batch;

/** 当前订单的总价格 */
@property (nonatomic, assign) float currentSumPrice;

/** 代表多少积分可以抵扣一元 */
@property (nonatomic, assign) int setuppoints;

/** 最高输入多少积分 */
@property (nonatomic, assign) int max_applay_points;

/**
 代表是否直接是 已完成支付
 */
@property (nonatomic) BOOL is_needspay;

/** 当前支付单号 */
@property (nonatomic, strong) NSString *pay_sn;

/** 当前支付模型 */
@property (nonatomic, strong) GYPayment *payModel;

/** 当前支付通知URL */
@property (nonatomic, strong) NSString *notifyUrl;

@end

@implementation GYConfirmOrderViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    //初始化
    [self setupUI];
}

- (void)viewWillLayoutSubviews {
    [super viewWillLayoutSubviews];
    self.payView.frame = CGRectMake(0, self.view.height-50-(iPhoneX ? 44 : 0), ScreenWidth, 50);
}

- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];

    //加载确认订单信息
    [self loadOrderInfo];
}

- (void)setupUI {
    self.storeMsg = @"";
    self.view.backgroundColor = RGBColor(245, 245, 245);
    self.navigationItem.title = @"确认订单";
    self.navigationItem.rightBarButtonItem = [UIBarButtonItem itemWithImage:@"more_b" tagret:self action:@selector(moreBtuClick) button:nil];
    //设置支付默认需要钱
    self.is_needspay = NO;
    
    //加载表格
    [self setupTbaleView];
    
    //监听支付通知
    [self registerPayNotification];
}

- (void)setupTbaleView {
    UITableView *tableView =[[UITableView alloc] initWithFrame:CGRectMake(0, 0, ScreenWidth, ScreenHeight-64-50-(iPhoneX ? 44 : 0)) style:UITableViewStyleGrouped];
    tableView.delegate = self;
    tableView.dataSource = self;
    tableView.tableFooterView = [[UIView alloc] initWithFrame:CGRectZero];
    tableView.tableHeaderView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, ScreenWidth, CGFLOAT_MIN)];
    tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
    tableView.sectionHeaderHeight = 0;
    tableView.sectionFooterHeight = 10;
    tableView.backgroundColor = [UIColor clearColor];
    
    [self.view addSubview:tableView];
    self.tableView = tableView;
    
    //加载付款视图
    [self setupPayView];
    
    //加载确认订单信息
    //[self loadOrderInfo];
}

- (void)loadOrderInfo {
    if (self.isDirectBuy) {//@"100664"
        NSString *cart_id = [NSString stringWithFormat:@"%@|%zd",self.goods_id,self.goodsCount];
        [self loadConfirmOrderInfo:@"" cart_id:cart_id address_id:self.addressModel.address_id == nil ? @"" : self.addressModel.address_id];
    }else {
        NSLog(@"购物车购买.....");
        NSString *cart_id = @"";
        for (GYShopingCart *cart in self.shopingCartList) {
            for (GYShopingCartGoods *goods in cart.goods) {
                //判断商品是否被选中
                if (goods.isSelectState) {
                    if (cart_id.length != 0) {
                        cart_id = [cart_id stringByAppendingFormat:@",%@|%@",goods.cart_id,goods.goods_num];
                    }else {
                        cart_id = [cart_id stringByAppendingFormat:@"%@|%@",goods.cart_id,goods.goods_num];
                    }
                }
            }
        }
        //NSLog(@"cart_id=======%@",cart_id);
        [self loadConfirmOrderInfo:@"1" cart_id:cart_id address_id:self.addressModel.address_id == nil ? @"" : self.addressModel.address_id];
    }
}

- (void)setupPayView {
    GYpayView *payView = [[[NSBundle mainBundle] loadNibNamed:@"GYpayView" owner:nil options:nil] firstObject];
    __weak typeof(self) weakSelf = self;
    payView.submintOrderInfoCallBack = ^(){
        //判断地址为不为空
        if (weakSelf.addressModel == nil) {
            [EasyTextView showText:@"请选择收货地址!"];
        }else {
            //提交订单这里要判断 需不需要输入密码
            if (weakSelf.is_needspay) {
                //判断用户有没有设置支付密码 (不需要支付现金)
                [GYNetWorkTools requestVerPayPwd:^(NSDictionary *obj) {
                    //NSLog(@"obj========%@",obj);
                    int code = [[obj objectForKey:@"code"] intValue];
                    if (code == 200) {
                        int datas = [[obj objectForKey:@"datas"] intValue];
                        if (datas == 1) {
                            [weakSelf setupPayPwdView];
                        }else {
                            [EasyTextView showText:@"您还没有设置支付密码!"];
                        }
                    }else if (code == 400) {
                        [EasyTextView showText:@"您还没有设置支付密码!"];
                    }
                } error:^(NSError *error) {
                    [EasyTextView showText:@"您的网络可能不太通畅..."];
                    NSLog(@"error=======%@",error);
                }];
            }else {
                //需要支付现金
                [EasyLodingView showLodingText:@"提交订单中..."];
                [self submitOrder];
            }
          
        }
    };
    
    [self.view addSubview:payView];
    self.payView = payView;
}

/**
 提交订单接口
 */
- (void)submitOrder{
    
    __weak typeof(self) weakSelf = self;
    //加载确认订单信息
    NSString *vat_hash = [weakSelf.cachesOrderInfo objectForKey:@"vat_hash"];
    NSString *offpay_hash = [weakSelf.cachesOrderInfo objectForKey:@"offpay_hash"];
    NSString *offpay_hash_batch = [weakSelf.cachesOrderInfo objectForKey:@"offpay_hash_batch"];
    NSString *pay_name = @"online";//有待更改
    NSString *cart_id = @"";
    
    if (weakSelf.isDirectBuy) {//@"100670"
        cart_id = [NSString stringWithFormat:@"%@|%zd",weakSelf.goods_id,weakSelf.goodsCount];
    }else {
        for (GYShopingCart *cart in weakSelf.shopingCartList) {
            for (GYShopingCartGoods *goods in cart.goods) {
                if (cart_id.length != 0) {
                    cart_id = [cart_id stringByAppendingFormat:@",%@|%@",goods.cart_id,goods.goods_num];
                }else {
                    cart_id = [cart_id stringByAppendingFormat:@"%@|%@",goods.cart_id,goods.goods_num];
                }
            }
        }
    }
    [GYNetWorkTools requestSubOrder:weakSelf.isDirectBuy ? @"" : @"1" cart_id:cart_id address_id:weakSelf.addressModel.address_id vat_hash:vat_hash offpay_hash:offpay_hash offpay_hash_batch:offpay_hash_batch pay_name:pay_name invoice_id:weakSelf.invoice_id == nil ? @"" : weakSelf.invoice_id pd_pay:@"" password:@"" fcode:@"" rcb_pay:@"" rpt:@"" points_orderprice:weakSelf.inputIngetral == nil ? @"" : weakSelf.inputIngetral pay_message:weakSelf.storeMsg == nil ? @"" : weakSelf.storeMsg is_needspay:weakSelf.is_needspay success:^(NSDictionary *obj) {
        NSLog(@"obj======%@",obj);
        int code = [[obj objectForKey:@"code"] intValue];
        NSDictionary *datas = [obj objectForKey:@"datas"];
        if (code == 200) {
            [EasyLodingView hidenLoding];
            NSString *pay_sn = [datas objectForKey:@"pay_sn"];
            //0.赋值
            weakSelf.pay_sn = pay_sn;
            //1.区分是否是完成订单
            if (weakSelf.is_needspay) {
                //0元提交订单接口
                [GYNetWorkTools reqeuestPayNeedspay:pay_sn success:^(NSDictionary *obj) {
                    //NSLog(@"obj =====%@",obj);
                    int code = [[obj objectForKey:@"code"] intValue];
                    if (code == 200) {
                      [weakSelf.navigationController popViewControllerAnimated:YES];
                    }else if (code == 400) {
                        [EasyTextView showText:@"提交订单错误,请稍后在提交!"];
                    }
                } error:^(NSError *error) {
                    [EasyTextView showText:@"亲,您的网络可能不太通畅..."];
                    NSLog(@"error====%@",error);
                }];
            }else {
                self.submit = YES;
                GYPayMethodSelectView *payMethodSelectView = [[[NSBundle mainBundle] loadNibNamed:@"GYPayMethodSelectView" owner:self options:nil] firstObject];
                payMethodSelectView.frame = [UIScreen mainScreen].bounds;
                payMethodSelectView.pay_sn = pay_sn;
                payMethodSelectView.orderPay = YES;
                payMethodSelectView.goods_price = self.payView.sumPriceLable.text;
                
                payMethodSelectView.returnPayMethodCallBack = ^(GYPayment *payMethod, NSString *notifyUrl) {
                    //赋值
                    weakSelf.payModel = payMethod;
                    weakSelf.notifyUrl = notifyUrl;
                    //跳转到支付监听界面 -----> 修改成直接在该页面监听支付
                    [self launchPay:payMethod pay_sn:pay_sn notifyUrl:notifyUrl];
//                    GYPayViewController *payVC = [[GYPayViewController alloc] initWithNibName:@"GYPayViewController" bundle:nil];
//                    payVC.model = payMethod;
//                    payVC.pay_sn = pay_sn;
//                    payVC.notifyUrl = notifyUrl;
//                    payVC.orderPay = NO;
//
//                    [weakSelf.navigationController pushViewController:payVC animated:YES];
                    
                    [weakSelf.payMethodSelectView removeFromSuperview];
                };
                payMethodSelectView.returnIsPayCallBack = ^(){
                    if (weakSelf.isSubmit) {
                        [weakSelf.navigationController popViewControllerAnimated:YES];
                    }
                };
                
                [[[UIApplication sharedApplication] keyWindow] addSubview:payMethodSelectView];
                weakSelf.payMethodSelectView = payMethodSelectView;
            }
        }else if (code == 400) {
            NSLog(@"error====%@",[datas objectForKey:@"error"]);
            self.submit = NO;
            [EasyTextView showText:@"提交订单出错,请稍后提交!"];
            [EasyLodingView hidenLoding];
        }
    } error:^(NSError *error) {
        self.submit = NO;
        NSLog(@"SubOrderFailed====%@",error);
        [EasyTextView showText:@"提交订单出错,请稍后提交!"];
        [EasyLodingView hidenLoding];
    }];
}

/**
 初始化支付密码
 */
- (void)setupPayPwdView {
    XLPasswordView *passwordView = [XLPasswordView passwordViewWithKeyboardType:XLPasswordViewKeyboardTypeSystem];
    passwordView.delegate = self;
    [passwordView showPasswordInView:self.view];
}

- (void)loadConfirmOrderInfo:(NSString *)ifcart cart_id:(NSString *)cart_id address_id:(NSString *)address_id {
    [EasyLodingView showLodingText:@"加载订单信息..."];
    [GYNetWorkTools requestConfirmOrderInfo:ifcart cart_id:cart_id address_id:address_id success:^(NSDictionary *obj) {
        //NSLog(@"加载订单信息obj======%@",obj);
        int code = [[obj objectForKey:@"code"] intValue];
        NSDictionary *datas = [obj objectForKey:@"datas"];
        self.cachesOrderInfo = datas;
        if (code == 200) {
            [EasyLodingView hidenLoding];
            //地址信息
            self.member_points = [[datas objectForKey:@"member_points"] intValue];
            self.storeList = [GYConfirmOrderStore jsonConfirmOrderStore:[datas objectForKey:@"store_cart_list"]];
            //我们应付总价格
             self.payView.sumPriceLable.text = [NSString stringWithFormat:@"¥%0.2f",[[datas objectForKey:@"store_final_total_list"] floatValue]];
            self.currentSumPrice = [[datas objectForKey:@"store_final_total_list"] floatValue];
            self.setuppoints = [[datas objectForKey:@"setuppoints"] intValue];
            self.max_applay_points = [[datas objectForKey:@"max_applay_points"] intValue];
            [self.tableView reloadData];
            if ([[datas objectForKey:@"address_info"] isKindOfClass:[NSDictionary class]]) {
                NSDictionary *address_info = [datas objectForKey:@"address_info"];
                self.addressModel = [[GYRecriveAddress alloc] initWithDic:address_info];
            }
            if (self.addressModel == nil) {
                UIAlertController *alertController = [UIAlertController alertControllerWithTitle:@"请添加地址" message:nil preferredStyle:UIAlertControllerStyleAlert];
                UIAlertAction *add = [UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
                    __weak typeof(self) weakSelf = self;
                    GYConfirmOrderAddressViewController *confirmOrderAddressVC = [[GYConfirmOrderAddressViewController alloc] initWithNibName:@"GYConfirmOrderAddressViewController" bundle:nil];
                    confirmOrderAddressVC.defaultSelectedAddress = weakSelf.addressModel;
                    confirmOrderAddressVC.returnSelectedReceiveAddressCallBack = ^(GYRecriveAddress *receiveAddress) {
                        weakSelf.addressModel = receiveAddress;
                        [weakSelf.tableView reloadData];
                    };
                    [weakSelf.navigationController pushViewController:confirmOrderAddressVC animated:YES];
                }];
                
                UIAlertAction *cancel = [UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:^(UIAlertAction * _Nonnull action) {
                    NSLog(@"取消....");
                }];
                
                [alertController addAction:add];
                [alertController addAction:cancel];
                
                [self  presentViewController:alertController animated:YES completion:nil];
                
                
            }
//            else {
//                [self.tableView reloadData];                
//            }
           
            
        }else if (code == 400) {
            NSLog(@"error========%@",[datas objectForKey:@"error"]);
            [EasyTextView showText:@"商品已下架或不存在"];
            [EasyLodingView hidenLoding];
            [self.navigationController popViewControllerAnimated:YES];
        }
        
    } error:^(NSError *error) {
        NSLog(@"laodConfirmOrderInfoFailed===%@",error);
        [EasyTextView showText:@"加载订单信息出错"];
        [EasyLodingView hidenLoding];
    }];
}

- (void)moreBtuClick {
    GYBasePopoverViewController *basePopoverVC = [[GYBasePopoverViewController alloc] initWithNibName:@"GYBasePopoverViewController" bundle:nil];
    __weak typeof(self) weakSelf = self;
    basePopoverVC.popoverViewSelectIndexCallBack = ^(NSInteger index) {
        switch (index) {
            case 0:
            {
                weakSelf.tabBarController.selectedIndex = 0;
                [weakSelf.tabBarController.tabBar setHidden:NO];
            }
                break;
                
            case 1:
            {
                GYSearchViewController *searchVC = [[GYSearchViewController alloc] init];
                [self.navigationController pushViewController:searchVC animated:YES];
            }
                break;
                
            case 2:
            {
                weakSelf.tabBarController.selectedIndex = 2;
                weakSelf.tabBarController.tabBar.hidden = YES;
            }
                break;
                
            case 3:
            {
                GYSystemMessageViewController *systemMessageVC = [[GYSystemMessageViewController alloc] initWithNibName:@"GYSystemMessageViewController" bundle:nil];
                [weakSelf.navigationController pushViewController:systemMessageVC animated:YES];
                
            }
                break;
                
            default:
                break;
        }
    };
    basePopoverVC.titles = @[@"首页",@"搜索",@"我的商城",@"消息"];
    basePopoverVC.images = @[@"home_w",@"search_w",@"ff_icon4",@"message_w"];
    
    self.animationDelegate = [[PopoverAnimation alloc] init];
    self.animationDelegate.popoverFrame = CGRectMake(ScreenWidth-widthScale(130, iphone6_W)-5, 50, widthScale(130, iphone6_W), basePopoverVC.titles.count*50);
    basePopoverVC.transitioningDelegate = (id)weakSelf.animationDelegate;
    
    basePopoverVC.modalPresentationStyle = UIModalPresentationCustom;
    [self presentViewController:basePopoverVC animated:YES completion:nil];
}

#pragma mark -- XLPasswordViewDelegate
/**
 *  输入密码位数已满时调用
 */
- (void)passwordView:(XLPasswordView *)passwordView didFinishInput:(NSString *)password
{
    NSLog(@"输入密码位数已满,在这里做一些事情,例如自动校验密码");
    [self.view endEditing:YES];
    //验证输密码正不正确
    [GYNetWorkTools requestcheckPassword:password success:^(NSDictionary *obj) {
        //NSLog(@"obj=====%@",obj);
        int code = [[obj objectForKey:@"code"] intValue];
        if (code == 200) {
            [passwordView removeFromSuperview];
            //首先提交订单  在提交0元支付的请求
            [self submitOrder];
        }else {
            [EasyTextView showText:@"您输入的密码不正确!"];
        }
    } error:^(NSError *error) {
        [EasyTextView showText:@"您的网络可能不太通畅!"];
        NSLog(@"error====%@",error);
    }];
}



#pragma mark -- UITableViewDelegate,UITableViewDataSource
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    return 4+self.storeList.count;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return 1;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    __weak typeof(self) weakSelf = self;
    if (indexPath.section < 3) {
        switch (indexPath.section) {
            case 0:
            {
                GYOrderAddressCell *cell = [GYOrderAddressCell cellWithTableView:tableView];
                cell.model = self.addressModel;
                
                return cell;
            }
                break;
                
            case 1:
            {
                GYorderSecondCell *cell = [GYorderSecondCell cellWithTableView:tableView];
                cell.payImageView.image = [UIImage imageNamed:@"mcc_01"];
                cell.payModeTitleLable.text = self.titles[indexPath.section-1];
                cell.paymodeLable.text = self.methods[indexPath.section-1];
                
                return cell;
                
                return cell;
            }
                break;
                
            case 2:
            {
                GYorderSecondCell *cell = [GYorderSecondCell cellWithTableView:tableView];
                cell.payImageView.image = [UIImage imageNamed:@"mcc_08_b"];
                cell.payModeTitleLable.text = self.titles[indexPath.section-1];
                cell.paymodeLable.text = self.methods[indexPath.section-1];
                
                return cell;
            }
                break;
                
        }
    }else if (indexPath.section < self.storeList.count+3 && indexPath.section>2){
        GYOrderGoodsCell *cell = [GYOrderGoodsCell cellWithTableView:tableView];
        cell.store = self.storeList[indexPath.row];
        cell.seeGoodsDetailsCallBack = ^(NSString *goods_id) {
            GYShopHomeViewController *shopHomeVC = [[GYShopHomeViewController alloc] init];
            shopHomeVC.goods_id = goods_id;
            [weakSelf.navigationController pushViewController:shopHomeVC animated:YES];
        };
        
        //店铺留言
        cell.storemessageCallBack = ^(NSString *msg) {
            weakSelf.storeMsg = msg;
        };
        
        return cell;
    }else {
        GYOrderIngetralCell *cell = [GYOrderIngetralCell cellWithTableView:tableView];
        cell.member_points = self.member_points;
        cell.setuppoints = self.setuppoints;
        __weak GYOrderIngetralCell *weakCell = cell;
        cell.ingetralCallBack = ^(NSString *ingetral) {
            // NSLog(@"ingetral=====%0.2f",self.currentSumPrice-[ingetral floatValue]);
            int integralCount = ingetral == nil ? 0 : [ingetral intValue];
            float payPrice = 0.00;
            float onePoint = 1.0/self.setuppoints;
            //判断输入的积分是不是大于 最大输入积分
            if (integralCount > self.max_applay_points) {
                [EasyTextView showText:[NSString stringWithFormat:@"本次交易最多使用%d积分",self.max_applay_points]];
                weakSelf.inputIngetral = [NSString stringWithFormat:@"%d",self.max_applay_points];
                //在这里要判断 输入的积分大小不能大于 钱数
                payPrice = self.currentSumPrice-self.max_applay_points*onePoint;
                
                //2.修改输入框中的积分数量
                weakCell.updatePoints = self.max_applay_points;
            }else {
                weakSelf.inputIngetral = [NSString stringWithFormat:@"%d",integralCount];
                //在这里要判断 输入的积分大小不能大于 钱数
                payPrice = self.currentSumPrice-integralCount*onePoint;
            }
            self.payView.sumPriceLable.text = [NSString stringWithFormat:@"%0.2f",payPrice];
            //3.判断是否是直接完成支付
            if (payPrice == 0) {
                //代表已完成支付
                self.is_needspay = YES;
                weakSelf.payView.updateBtuTitle = YES;
            }else {
                self.is_needspay = NO;
                weakSelf.payView.updateBtuTitle = NO;
            }
        };
        
        return cell;
    }
    return nil;
}
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
    
    __weak typeof(self) weakSelf = self;
    switch (indexPath.section) {
        case 0:
        {
            GYConfirmOrderAddressViewController *confirmOrderAddressVC = [[GYConfirmOrderAddressViewController alloc] initWithNibName:@"GYConfirmOrderAddressViewController" bundle:nil];
            confirmOrderAddressVC.defaultSelectedAddress = weakSelf.addressModel;
            confirmOrderAddressVC.returnSelectedReceiveAddressCallBack = ^(GYRecriveAddress *receiveAddress) {
                weakSelf.addressModel = receiveAddress;
                [tableView reloadData];
            };
            [weakSelf.navigationController pushViewController:confirmOrderAddressVC animated:YES];
        }
            break;
        
        case 1:
        {
            GYPayMethodViewController *payMethodVC = [[GYPayMethodViewController alloc] initWithNibName:@"GYPayMethodViewController" bundle:nil];
            payMethodVC.selectPayMethodCallBack = ^(NSString *title) {
                [weakSelf.methods replaceObjectAtIndex:indexPath.section-1 withObject:title];
                [weakSelf.tableView reloadData];
            };
            [self.navigationController pushViewController:payMethodVC animated:YES];

        }
            break;
            
        case 2:
        {
            //跳转到发票界面
            GYInvoiceViewController *invotionVC = [[GYInvoiceViewController alloc] initWithNibName:@"GYInvoiceViewController" bundle:nil];
            invotionVC.returnSelectInvoiceCallBack = ^(NSString *invoice,NSString *invoice_id) {
                
                weakSelf.invoice_id = invoice_id;
                [weakSelf.methods replaceObjectAtIndex:indexPath.section-1 withObject:invoice];
                
                [tableView reloadSections:[NSIndexSet indexSetWithIndex:indexPath.section] withRowAnimation:UITableViewRowAnimationNone];
            };
            [self.navigationController pushViewController:invotionVC animated:YES];

        }
            break;
            
        default:
            break;
    }
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    
    if (indexPath.section < 3) {
        if (indexPath.section == 0) {
            GYOrderAddressCell *cell = [GYOrderAddressCell cellWithTableView:tableView];
            return [cell height:self.addressModel];
        }else {
            return 44;
        }
        
    }else if (indexPath.section < self.storeList.count+3 && indexPath.section>2) {
        GYOrderGoodsCell *cell = [GYOrderGoodsCell cellWithTableView:tableView];
        return [cell height:self.storeList[indexPath.row]];
    }else {
        GYOrderIngetralCell *cell = [GYOrderIngetralCell cellWithTableView:tableView];
        return [cell height];
    }
}

- (UIView *)tableView:(UITableView *)tableView viewForFooterInSection:(NSInteger)section {
    UIView *view = [[UIView alloc] initWithFrame:CGRectMake(0, 0, ScreenWidth, 10)];
    view.backgroundColor = [UIColor clearColor];
    
    return view;
}

#pragma mark --  支付

/**
 注册支付是否成功的监听
 */
- (void)registerPayNotification {
    //监听是微信否支付成功
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(WeiXinPaySuccess) name:WeiXinPaySuccess object:nil];
    
    //监听微信支付取消
    [[NSNotificationCenter defaultCenter]addObserver:self selector:@selector(WeiXinPayCancel) name:WeiXinPayCanacel object:nil];
    
    //监听支付宝是否支付成功
    [[NSNotificationCenter defaultCenter]addObserver:self selector:@selector(zhifubaoPaySuccess:) name:zhifubaoPaySuccess object:nil];
}

/**
 移除支付方面的监听
 */
- (void)removePayNotification {
    [[NSNotificationCenter defaultCenter] removeObserver:self name:WeiXinPaySuccess object:nil];
    [[NSNotificationCenter defaultCenter] removeObserver:self name:WeiXinPayCanacel object:nil];
    [[NSNotificationCenter defaultCenter] removeObserver:self name:zhifubaoPaySuccess object:nil];
}

/**
 发起支付
 */
- (void)launchPay:(GYPayment *)model pay_sn:(NSString *)pay_sn notifyUrl:(NSString *)notifyUrl {
    if ([model.payment_id intValue] == 1) {
        //NSLog(@"支付宝支付....");
        [GYNetWorkTools requestLaunchPay:pay_sn payment_code:model.payment_code success:^(NSDictionary *obj) {
            //NSLog(@"zhifubao  =======%@",obj);
            int code = [[obj objectForKey:@"code"] intValue];
            if (code == 200) {
                NSString *datas = [obj objectForKey:@"datas"];
                [[AlipaySDK defaultService] payOrder:datas fromScheme:@"zhifubao" callback:^(NSDictionary *resultDic) {
                    NSLog(@"resultDic====%@",resultDic);
                }];
            }else if (code == 400) {
                [EasyTextView showText:@"支付失败请,请重新支付!"];
                [self.navigationController popViewControllerAnimated:YES];
            }
        } error:^(NSError *error) {
            [EasyTextView showText:@"支付失败请,请重新支付!"];
            [self.navigationController popViewControllerAnimated:YES];
            [EasyLodingView hidenLoding];
            NSLog(@"LaunchPayzhifubaoFailed=====%@",error);
        }];
    }else if ([model.payment_id intValue] == 2) {
        //NSLog(@"微信支付....");
        [GYNetWorkTools requestWeiXinPay:pay_sn payment_code:model.payment_code wxpay_appid:[model.payment_config objectForKey:@"wxpay_appid"] wxpay_mch_id:[model.payment_config objectForKey:@"wxpay_mch_id"] wxpay_key:[model.payment_config objectForKey:@"wxpay_key"] notifyUrl:notifyUrl success:^(NSDictionary *obj) {
            //NSLog(@"obj----=====%@",obj);
            int code = [[obj objectForKey:@"code"] intValue];
            NSDictionary *datas = [obj objectForKey:@"datas"];
            if (code == 200) {
                PayReq *request = [[PayReq alloc] init];
                request.partnerId = [datas objectForKey:@"partnerid"];
                request.prepayId= [datas objectForKey:@"prepayid"];
                request.package = [datas objectForKey:@"package"];
                request.nonceStr= [datas objectForKey:@"noncestr"];
                request.timeStamp= (UInt32)[[datas objectForKey:@"timestamp"] longLongValue];
                request.sign= [datas objectForKey:@"sign"];
                [WXApi sendReq:request];
            }else {
                NSLog(@"error======%@",[[datas objectForKey:@"error"] objectForKey:@"return_msg"]);
            }
        } error:^(NSError *error) {
            NSLog(@"WeiXinPayError");
        }];
    }
}

/**
 微信取消支付回调方法
 */
- (void)WeiXinPayCancel {
    NSLog(@"微信支付取消...");
    [self.navigationController popToRootViewControllerAnimated:YES];
}

/**
 微信支付成功回调方法
 */
- (void)WeiXinPaySuccess {
    NSLog(@"微信支付成功回调...");
    [GYNetWorkTools requestWeiXinPaySuccess:self.pay_sn payment_code:self.payModel.payment_code wxpay_appid:[self.payModel.payment_config objectForKey:@"wxpay_appid"] wxpay_mch_id:[self.payModel.payment_config objectForKey:@"wxpay_mch_id"] wxpay_key:[self.payModel.payment_config objectForKey:@"wxpay_key"] notifyUrl:self.notifyUrl success:^(NSDictionary *obj) {
        //NSLog(@"obj========%@",obj);
        int code = [[obj objectForKey:@"code"] intValue];
        NSDictionary *data = [obj objectForKey:@"datas"];
        if (code == 200) {
            [self.navigationController popToRootViewControllerAnimated:YES];
        }else if (code == 400) {
            NSLog(@"error==========%@",[data objectForKey:@"error"]);
            [EasyTextView showText:@"支付失败,请重新支付!"];
            [self.navigationController popToRootViewControllerAnimated:YES];
        }
    } error:^(NSError *error) {
        [EasyTextView showText:@"支付失败,请重新支付!"];
        [self.navigationController popToRootViewControllerAnimated:YES];
        NSLog(@"WeiXinPaySuccesFailed======%@",error);
    }];
    
    //这里要返回订单查询界面或则 上平界面
}

/**
 支付宝成功回调方法

 @param noti <#noti description#>
 */
- (void)zhifubaoPaySuccess:(NSNotification *)noti {
    NSLog(@"支付宝支付成功回调");
    NSDictionary *payResult = noti.object;
    int resultStatus = [[payResult objectForKey:@"resultStatus"] intValue];
    if (resultStatus == 9000) {
        //代表支付成功
        NSDictionary *result = [NSJSONSerialization JSONObjectWithData:[[payResult objectForKey:@"result"] dataUsingEncoding:NSUTF8StringEncoding] options:NSJSONReadingMutableLeaves error:nil];
        NSDictionary *alipay_trade_app_pay_response = [result objectForKey:@"alipay_trade_app_pay_response"];
        NSString *trade_no = [alipay_trade_app_pay_response objectForKey:@"trade_no"];
        NSString *out_trade_no = [alipay_trade_app_pay_response objectForKey:@"out_trade_no"];
        
        [GYNetWorkTools requestZhifubaoPaySuccess:out_trade_no trade_no:trade_no uccess:^(NSDictionary *obj) {
            //NSLog(@"obj========%@",obj);
            int code = [[obj objectForKey:@"code"] intValue];
            if (code == 200) {
                NSLog(@"支付宝支付完成通知完成!");
                [self.navigationController popToRootViewControllerAnimated:YES];
            }else {
                NSLog(@"支付宝支付完成通知有误!");
            }
        } error:^(NSError *error) {
            NSLog(@"支付宝支付完成通知有误!");
            
            [self.navigationController popToRootViewControllerAnimated:YES];
            
        }];
    }else {
        //代表支付失败
        [self.navigationController popToRootViewControllerAnimated:YES];
    }
}


#pragma mark -- 懒加载

- (NSArray *)titles {
    if (!_titles) {
        _titles = @[@"支付方式:",@"发票信息:"];
    }
    
    return _titles;
}

- (NSMutableArray *)methods {
    if (!_methods) {
        _methods = [NSMutableArray arrayWithObjects:@"在线付款",@"不需要发票", nil];
    }
    
    return _methods;
}

- (NSMutableDictionary *)cachesStoreMsg {
    if (!_cachesStoreMsg) {
        _cachesStoreMsg = [NSMutableDictionary dictionary];
    }
    
    return _cachesStoreMsg;
}

- (void)dealloc {
    [self.payMethodSelectView removeFromSuperview];
    //删掉监听支付通知
    [self removePayNotification];
    NSLog(@"GYConfirmOrderViewController ===== dealloc");
}
@end
